package com.hhd.pdf.components.eq;

import com.hhd.pdf.CommonUtils;
import com.hhd.pdf.components.AbstractInLineBlockComponent;
import com.hhd.pdf.context.GeneratorContext;
import com.hhd.pdf.variable.CompositeFormula;
import com.hhd.pdf.variable.VariableContext;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import org.dom4j.tree.DefaultElement;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Component
public class EqComponent extends AbstractInLineBlockComponent {
    @Override
    public List<Element> createElements(org.dom4j.Element element,
                                        GeneratorContext context,
                                        VariableContext rootVariableContext) throws DocumentException, IOException {
        String var1 = element.attributeValue("var1");
        String var2 = element.attributeValue("var2");

        CompositeFormula formula1 = CompositeFormula.formula(var1);
        CompositeFormula formula2 = CompositeFormula.formula(var2);

        formula1.execute(rootVariableContext);
        formula2.execute(rootVariableContext);

        if (formula2.joinFormulas().equals(formula1.joinFormulas()))
            return createPdfElementsByVariableContext(rootVariableContext, element, context);
        return CommonUtils.newList();
    }

    @Override
    public void parseComponent(org.dom4j.Element element, GeneratorContext context) throws Exception {
        context.getDocument()
                .addAll(createElements(element, context, context.createRootVariableContext()));
    }

    @Override
    public String getFormula(DefaultElement defaultElement) {
        return defaultElement.asXML();
    }

    @Override
    public String getName() {
        return "eq";
    }
}
